package com.neuedu.jdboot.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.neuedu.jdboot.bean.Privilege;
import com.neuedu.jdboot.bean.Role;
import com.neuedu.jdboot.bean.RolePrivilege;
import com.neuedu.jdboot.common.JdbootException;
import com.neuedu.jdboot.mapper.PrivilegerMapper;
import com.neuedu.jdboot.mapper.RoleMapper;
import com.neuedu.jdboot.service.RoleService;

/**
 * 
 * @author chens
 *
 */
@Service
@Transactional(rollbackFor = JdbootException.class)
public class RoleServiceImpl extends DefaultServiceImpl<Role> implements RoleService {
	private Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private PrivilegerMapper privilegerMapper;

	@Override
	public List<Privilege> findByRole(Integer roleId) {

		List<Privilege> ret = new ArrayList<Privilege>();

		try {
			// 查询一级权限
			ret = privilegerMapper.findByRole(roleId, null);
			logger.info("=================1===========================");
			// 查询二级权限
			// TODO 目前只支持二级权限
			for (Privilege privilege : ret) {
				logger.info(privilege.getId().toString());

				List<Privilege> subList = privilegerMapper.findByRole(roleId, privilege.getId());
				logger.info(subList.toString());

				privilege.setSubList(subList);
			}
		} catch (Exception e) {
			throw new JdbootException("查询异常", e);
		}
		return ret;
	}

	@Override
	public boolean deletePrivilegesByRole(Integer roleId) {

		boolean ret = false;
		try {
			ret = privilegerMapper.deletePrivilegesByRole(roleId);
		} catch (Exception e) {
			throw new JdbootException("删除异常", e);
		}
		return ret;
	}

	@Override
	public boolean addRolePrivilege(List<RolePrivilege> list) {

		boolean ret = false;
		try {
			ret = privilegerMapper.addRolePrivilege(list);
		} catch (Exception e) {
			throw new JdbootException("新增异常", e);
		}
		return ret;
	}

	@Override
	public List<Role> findList() {

		List<Role> ret = new ArrayList<>();

		try {
			ret = roleMapper.findList();
		} catch (Exception e) {
			throw new JdbootException("查询异常", e);
		}
		return ret;
	}

	@Override
	public boolean add(Role role) {
		boolean ret = false;
		ret = super.add(role);
		if (ret) {
			List<RolePrivilege> list = new ArrayList<RolePrivilege>();
			for (Privilege privilege : role.getPrivileges()) {
				list.add(new RolePrivilege(role.getId(), privilege.getId()));
			}
			ret &=this.addRolePrivilege(list);
		}

		return ret;
	}

}
